package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.context.BaseContext;
import com.example.dto.FilesPageDTO;
import com.example.entity.Bindfiles;
import com.example.entity.Homework;
import com.example.entity.Login;
import com.example.mapper.BindfilesMapper;
import com.example.mapper.HomeworkMapper;
import com.example.mapper.LoginMapper;
import com.example.result.PageResult;
import com.example.service.IBindfilesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.utils.BaseException;
import com.example.utils.CommonControllers;
import com.example.vo.BindfilesVO;
import com.example.vo.ModelfilesVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈昌吉
 * @since 2024-04-16
 */
@Service
public class BindfilesServiceImpl extends ServiceImpl<BindfilesMapper, Bindfiles> implements IBindfilesService {

    @Autowired
    private CommonControllers commonControllers;
    @Autowired
    private BindfilesMapper bindfilesMapper;
    @Autowired
    HomeworkMapper homeworkMapper;
    @Autowired
    private LoginMapper loginMapper;

    /**
     * 上传绑定文件相关接口
     * @param file
     * @param hid
     * @return
     */
    @Override
    public List<Bindfiles> insert(MultipartFile file, Integer hid) {

        //判断作业上交时间是否截止
        Homework homework = homeworkMapper.selectById(hid);
        System.out.println(LocalDateTime.now().isBefore(homework.getEndtime()));
        if (LocalDateTime.now().isBefore(homework.getEndtime())==false){
            throw new BaseException("作业时间已结束，不能在提交",500);
        }
        String originalFilename = file.getOriginalFilename();//获取文件原始名称
        //String s = FileUtil.mainName(originalFilename);//获取文件前面名不含后缀
        //String s1 = FileUtil.extName(originalFilename);//获取文件后缀名

        //判断文件名是否重复
        QueryWrapper<Bindfiles> bindfilesQueryWrapper = new QueryWrapper<>();
        List<Bindfiles> modelname = bindfilesMapper.selectList(bindfilesQueryWrapper.eq("name", originalFilename));
        if(modelname.size()!=0){
            throw new BaseException("该文件已存在，不能重复上传",500);
        }

        String upload = String.valueOf(commonControllers.upload(file));//获取返回的url

        Bindfiles build = Bindfiles.builder()
                .url(upload)
                .hid(hid)
                .loginId(BaseContext.getCurrentId())
                .name(originalFilename)
                .uploadtime(LocalDateTime.now())
                .build();
        bindfilesMapper.insert(build);

        List<Bindfiles> bindfiles = bindfilesMapper.selectList(bindfilesQueryWrapper.eq("login_id", BaseContext.getCurrentId()).eq("hid", hid));

        return bindfiles;
    }

    /**
     * 根据作业ID和学生ID获取上交作业
     * @param hid
     * @return
     */
    @Override
    public List<Bindfiles> select(Integer hid) {
        QueryWrapper<Bindfiles> wrapper = new QueryWrapper<>();
        List<Bindfiles> bindfiles = bindfilesMapper.selectList(wrapper.eq("hid", hid).eq("login_id",BaseContext.getCurrentId()));

        return bindfiles;
    }

    /**
     * 根据ID删除绑定文件相关接口
     * @param bindfiles
     */
    @Override
    public void deleteById(Bindfiles bindfiles) {

        commonControllers.delete(bindfiles.getUrl());
        bindfilesMapper.deleteById(bindfiles);
    }

    @Override
    public PageResult selectAll(FilesPageDTO filesPageDTO) {

        //通过登录ID查询账号角色
        Login login = loginMapper.selectByID(BaseContext.getCurrentId());

        //判断当前角色0（老师）,1（助教）,2（学生）
        if (login.getRole().equals("0")){
            filesPageDTO.setSta("合格");
        }else if (login.getRole().equals("1")){
            filesPageDTO.setSta("待审核");
        }else{
            return null;
        }

        //开始分页查询
        PageHelper.startPage(filesPageDTO.getPageNum(), filesPageDTO.getPageSize());

        Page<BindfilesVO> page = bindfilesMapper.selectAll(filesPageDTO.getHid(),filesPageDTO.getSta(),filesPageDTO.getState());

        long total = page.getTotal();
        List<BindfilesVO> records = page.getResult();

        return new PageResult(total, records);


    }

    @Override
    public void updateBindFiles(Bindfiles bindfiles) {
        bindfilesMapper.updateBindFiles(bindfiles);
    }
}
